package cn.bgs.service.impl;

import cn.bgs.common.MD5;
import cn.bgs.common.R;
import cn.bgs.mapper.StyleShowMapper;
import cn.bgs.mapper.UserMapper;
import cn.bgs.pojo.StyleShow;
import cn.bgs.pojo.User;
import cn.bgs.service.UserService;
import cn.bgs.vo.TokenPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<StyleShowMapper, StyleShow> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     */
    @Override
    public R login(String userName, String password) {

        User user = userMapper.login(userName);

        if (user!=null){
            if (MD5.encrypt(password).equals(user.getPassword())){

                UUID token= UUID.randomUUID();

                TokenPage tokenPage = new TokenPage();

                tokenPage.setLoginUser(userName);

                String s = token.toString();
                
                tokenPage.setToken(s);

                userMapper.addToken(tokenPage);

                return R.ok().data("userinfo",user);
            }else {
                return R.error().data("error","密码错误");
            }
        }else {
            return R.error().data("error","用户不存在");
        }

    }

    /**
     * 注册
     * @param userName
     * @param password
     * @return
     */
    @Override
    public R register(String userName, String password) {

        User user = userMapper.login(userName);

        if (user == null){
            Integer i = userMapper.register(userName,MD5.encrypt(password));
            if (i!=0){
                return R.ok();
            }else {
                return R.error().data("error","注册失败");
            }
        }else {
            return R.error().data("error","用户已存在");
        }
    }
}
